<?php

/**
 * URI分析类
 * 
 * @package    01CMS
 * @subpackage system
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class Uri
{
    private $className;
    private $methodName;
    private $param;
    private $pathInfo = '';

    function __construct ()
    {
        if (! empty($_GET['i']))
        {
            $this->pathInfo = $_GET['i'];
        }
        else if (! empty($_SERVER['PATH_INFO']))
        {
            $this->pathInfo = $_SERVER['PATH_INFO'];
        }
        
        if ($this->pathInfo != '')
        {
            $this->pathInfo = trim($this->pathInfo, '/');
            $urlSuffix = $GLOBALS['Load']->config['urlSuffix'];
            if (! empty($urlSuffix))
            {
                $this->pathInfo = preg_replace($urlSuffix . '$', '', $this->pathInfo);
            }
            $uriArr = explode("/", $this->pathInfo);
            $segments = array();
            foreach ($uriArr as $val)
            {
                $val = trim($this->filterSegment($val));
                if ($val != '')
                {
                    $segments[] = $val;
                }
            }
            $this->className = empty($segments[0]) ? '' : ucfirst($segments[0]);
            $this->methodName = empty($segments[1]) ? '' : $segments[1];
            $this->param = isset($segments[2]) ? array_slice($segments, 2) : array();
        }
    }

    private function filterSegment ($str)
    {
        if (substr($str, 0, 1) == '_')
        {
            showError('Bad Request');
        }
        $bad = array('$', '(', ')', '%28', '%29');
        $good = array('&#36;', '&#40;', '&#41;', '&#40;', '&#41;');
        $str = str_replace($bad, $good, $str);
        $str = slashQuotes($str);
        return $str;
    }

    public function getClassName ()
    {
        return empty($this->className) ? 'index' : strtolower($this->className);
    }

    public function getMethodName ()
    {
        return empty($this->methodName) ? 'index' : $this->methodName;
    }

    public function getParam ()
    {
        return $this->param;
    }

    public function getPathInfo ()
    {
        return $this->pathInfo;
    }
}